---
import BaseHead from '../../components/BaseHead.astro';
import Header from '../../components/Header.astro';
import Footer from '../../components/Footer.astro';
import { SITE_TITLE, SITE_DESCRIPTION } from '../../consts';
import { auth } from '../../libs/lucia';
import { LuciaError } from "lucia";

const { locale } = Astro.params;
let errorMessage: string | null = null;
let emailInput = "";

if (Astro.request.method === "POST") {
    // const response = await fetch("https://www.baidu.com/", { method: 'POST' });
    // console.log(await response.text())
	const formData = await Astro.request.formData();
	const email = formData.get("email");
	const password = formData.get("password");
    try {
        // find user by key
        // and validate password
        const key = await auth.useKey("email", email.toLowerCase(), password);
        console.log(key)
        const session = await auth.createSession({
            userId: key.userId,
            attributes: {
                email: key.providerUserId
            }
        });
        console.log(key, session)
        Astro.locals.auth.setSession(session); // set session cookie
        return Astro.redirect("/", 302); // redirect to profile page
    } catch (e) {
        console.log(e)
        if (
            e instanceof LuciaError &&
            (e.message === "AUTH_INVALID_KEY_ID" ||
                e.message === "AUTH_INVALID_PASSWORD")
        ) {
            // user does not exist
            // or invalid password
            errorMessage = "Incorrect email or password";
            Astro.response.status = 400;
        } else {
            errorMessage = "An unknown error occurred";
            Astro.response.status = 500;
        }
    }
}
---

<!doctype html>
<html lang={locale}>
	<head>
		<meta charset="utf-8" />
		<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
		<meta name="viewport" content="width=device-width" />
		<meta name="generator" content={Astro.generator} />
		<title>Email & password auth with Lucia</title>
	</head>
	<body>
		<h1>Sign in</h1>
		<form method="post">
			<label for="email">Email</label>
			<input name="email" id="email" value={emailInput} /><br />
			<label for="password">Password</label>
			<input type="password" name="password" id="password" /><br />
			<input type="submit" />
		</form>
		<p class="error">{errorMessage}</p>
		<a href="/password-reset">Reset password</a>
		<a href={`/${locale}/signup`}>Create an account</a>
		<a href="/login/github">Sign in with GitHub</a>
	</body>
</html>
